import { ref } from "vue"
import { ElMessageBox } from "element-plus"
import { uploadFile } from "/plugins/file"
import { allIndexedDBIcons, setIndexedDBIcon, removeIndexedDBIcon } from "./indexedDB"
export function useUpload(selectIcon) {
	const useIcons = ref([])
	;(async () => (useIcons.value = await allIndexedDBIcons()))()
	async function upload(event) {
		const e = event
		if (e.target.files) {
			toUpload(e.target.files[0])
		}
	}
	async function toUpload(files) {
		try {
			const result = await uploadFile(files)
			if (!result) return
			selectIcon(result.url)
			const type = await setIndexedDBIcon(result.url)
			if (type?.type !== "existing") {
				useIcons.value.push(result.url)
			}
		} catch (error) {
			console.log("select-icon: 上传图标报错: ", error)
		}
	}
	async function deleteIcon(url, index) {
		await ElMessageBox.confirm("确定删除该图标？", "提示", {
			type: "warning",
		})
		await removeIndexedDBIcon(url)
		useIcons.value.splice(index, 1)
	}
	return {
		useIcons,
		upload,
		deleteIcon,
	}
}
